package com.sulong.service;

import com.sulong.Column;
import com.sulong.Table;
import com.sulong.dao.ColumnPo;
import com.sulong.dao.DaoInterface;
import com.sulong.entity.DataProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class GenerateDocuments {
    @Autowired
    DaoInterface daoInterface;
    @Autowired
    DataProperties dataProperties;

    public void generateDocuments(){
        String dataBaseName = dataProperties.getDataBaseName();
        List<Table> tableList = daoInterface.getAllTable(dataBaseName);

        for (Table table : tableList) {
            String name = table.getName();
            name.replaceAll("\"", "");
            List<ColumnPo> columnPos = daoInterface.getColumnsByTableName(dataBaseName +"." + table.getName());
            ArrayList<Column> columns = new ArrayList<>();
            for (ColumnPo columnPo : columnPos) {
                Column column = new Column();
                BeanUtils.copyProperties(columnPo, column);
                column.setDefaultValue(columnPo.getDefault());
                column.setComment(columnPo.getComment());
                column.setIsNull(columnPo.getNull().equalsIgnoreCase("NO") ? "不为空" : "可以");
                column.setKey("PRI".equalsIgnoreCase(columnPo.getKey()) ? "主键" : "");
                columns.add(column);
            }
            for (Column column : columns) {
                String type = column.getType();
                if (type.indexOf(",") > 0) {
                    String decimal = type.split(",")[1];
                    if (decimal.indexOf(")") > 0) {
                        String decimalPlace = decimal.split("\\)")[0];
                        column.setDecimalPlace(decimalPlace);
                    }
                }
                if (type.indexOf("(") > 0) {
                    String fieldLength = "";
                    String len = type.split("\\(")[1];
                    String len2 = len.split("\\)")[0];
                    if (len2.indexOf(",") > 0) {
                        fieldLength = len2.split(",")[0];
                    } else {
                        fieldLength = len2;
                    }
                    column.setFieldLength(fieldLength);
                }
                if (type.indexOf("(") > 0) {
                    type = type.split("\\(")[0];
                    column.setType(type);
                }
            }
            table.setColumns(columns);
        }
        generateFile(tableList,dataBaseName);
    }
    public  void generateFile(List<Table> tableList,String dataBaseName) {
        // step1 创建freeMarker配置实例
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            configuration.setDefaultEncoding("UTF-8");
            // step2 获取模版路径
            configuration.setClassForTemplateLoading(GenerateDocuments.class,"/static");
            // step3 创建数据模型
            Map<String, Object> result = new HashMap<>();
            result.put("tableList", tableList);
            result.put("dataBaseName", dataBaseName);

            // step4 加载模版文件
            Template template = configuration.getTemplate("DBDocument.ftl");
            // step5 生成数据
            javax.swing.filechooser.FileSystemView fsv = javax.swing.filechooser.FileSystemView
                    .getFileSystemView();
            File docFile = new File(fsv.getHomeDirectory() + "\\" + dataBaseName+"数据库设计文档.html");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile),"UTF-8"));
            // step6 输出文件
            template.setOutputEncoding("UTF-8");
            template.process(result, out);

            System.out.println("数据库设计文档生成成功 !");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}
